import { Router } from 'express'
import UserDao from '../../dao/UserDao.js'
import User from '../../verify/User.js'

let router = Router()

router.post('/api/admin/login', async (req, res) => {
    let user = User.login(req.body)
    if (!user) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

    let result = await UserDao.selectByUsernameAndPassword(user.username, user.password)
    if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

    if (result.user_status !== 1) return res.end(JSON.stringify({ code: 500, msg: '账号已冻结' }))

    result.password = '**********'
    req.session.user = result

    return res.end(JSON.stringify({ code: 200, data: result }))
})

router.get('/api/admin/logout', async (req, res) => {
    if (req.session.user) req.session.user = null

    return res.end(JSON.stringify({ code: 200, msg: '退出登录成功' }))
})

router.post('/api/admin/register', async (req, res) => {
    let user = User.insertObj(req.body)
    if (!user) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

    let result = await UserDao.insert(user)
    if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

    return res.end(JSON.stringify({ code: 200 }))
})

export default router